import React, { Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import { router } from 'umi';
import _ from 'lodash';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Card,
    Row,
    Col,
    Input,
    Button,
    Descriptions,
    Modal,
    message,
    Space,
} from 'antd';
import { ZoomInOutlined, ZoomOutOutlined } from '@ant-design/icons';

interface OcrCheckProps extends FormComponentProps {
    loading: boolean;
    dispatch: Dispatch<any>;
    location: { query: any },
    detailInfo: any;
    match: { params: { fid: number } },
}

interface OcrCheckState {
    rotatingDegree: number;
    imgSize: number;
    countVisible: boolean;
    confirmVisible: boolean;
    behalfVisible: boolean;
}

@connect(({
    ocrCheckDetail: { detailInfo, hasCheck },
}: any) => ({ detailInfo, hasCheck }))

class ocrCheckInfo extends React.Component<OcrCheckProps, OcrCheckState> {
    state = {
        rotatingDegree: 0,
        imgSize: 1,
        countVisible: false,
        confirmVisible: false,
        behalfVisible: false,
    }

    componentDidMount() {
        this.fetchDetail();
        window.addEventListener('keydown', this.handleOnKeyDownConfirm);
    }

    componentDidUpdate(prevProps: any) {
        const { detailInfo } = this.props;
        const { consigneePhone } = detailInfo;

        if (!_.isEqual(detailInfo, prevProps.detailInfo)) {
            const { form: { setFieldsValue } } = this.props;
            setFieldsValue({ consigneePhone });
        }

    }

    componentWillUnmount() {
        document.removeEventListener("keydown", this.handleOnKeyDownConfirm);
    }

    fetchDetail = () => {
        const { location: { query: { logisId, expressId } } } = this.props;

        if (logisId) {
            const { dispatch } = this.props;
            dispatch({
                type: 'ocrCheckDetail/fetch',
                payload: { logisId, expressId },
            });
        } else {
            message.warning('请先选择物流中心！');
            router.replace('/logisCenter/ocrCheck/logis');
        }
    }

    handleShowCountModal = () => {
        this.setState({ countVisible: true });
    };

    handleCloseCountModal = () => {
        this.setState({ countVisible: false });
    }

    handleSetCounting = () => {
        const {
            location: { query: { logisId } },
            detailInfo: { id: orderId },
        } = this.props;

        const { dispatch } = this.props;
        dispatch({
            type: 'ocrCheckDetail/setCounting',
            payload: {
                logisId: Number(logisId),
                orderId,
            },
        });

        this.handleCloseCountModal();
    }

    handleShowConfirmModal = (confirmVisible: boolean) => {
        const { form: { getFieldValue } } = this.props;
        const consigneePhone = getFieldValue('consigneePhone');
        message.destroy();
        if (confirmVisible && !consigneePhone) {
            message.error('请补录11位手机号');
        } else if (!/^1[3456789]\d{9}$/.test(consigneePhone)) {
            message.error('手机号格式错误');
        } else {
            this.setState({ confirmVisible });
        }
    }

    handleShowBehalfConfirmModal = (behalfVisible: boolean) => {
        this.setState({ behalfVisible });
    }

    handleOnKeyDownConfirm = (event: any) => {

        if (event.keyCode === 13) this.handleConfirm();
    }

    handleConfirm = () => {
        const {
            location: { query: { logisId, expressId } },
            detailInfo: { id: orderId },
            form: { getFieldValue },
        } = this.props;
        const consigneePhone = getFieldValue('consigneePhone');

        if (!consigneePhone) {
            message.error('请补录11位手机号');
            return;
        } else if (!/^1[3456789]\d{9}$/.test(consigneePhone)) {
            message.error('手机号格式错误');
            return;
        } else {
            const { dispatch } = this.props;
            dispatch({
                type: 'ocrCheckDetail/confirm',
                payload: {
                    logisId,
                    expressId,
                    orderId,
                    consigneePhone,
                },
            });

            this.handleShowConfirmModal(false);
        }
    }

    handleBehalfConfirm = () => {
        const {
            location: { query: { logisId, expressId } },
            detailInfo: { id: orderId },
            form: { getFieldValue },
        } = this.props;
        const consigneePhone = getFieldValue('consigneePhone');

        const { dispatch } = this.props;
        dispatch({
            type: 'ocrCheckDetail/behalfConfirm',
            payload: {
                logisId,
                expressId,
                orderId,
                consigneePhone,
            },
        });

        this.handleShowBehalfConfirmModal(false);
    }

    // 旋转图片
    handleRotating = (degree: number) => {
        let { rotatingDegree } = this.state;
        rotatingDegree += degree;
        this.setState({ rotatingDegree }, () => this.setImgStyle());
    }

    // 放大缩小图片
    handleChangeImgSize = (size: number) => {
        const { imgSize } = this.state;
        const new_imgSize = imgSize + size;
        this.setState({
            imgSize: new_imgSize <= 0.2 ? imgSize : new_imgSize,
        }, () => this.setImgStyle());
    }

    // 设置图片style
    setImgStyle = () => {
        const { rotatingDegree, imgSize } = this.state;
        const img: any = document.getElementById('img');
        img.style.transform = `scale(${imgSize}) rotate(${rotatingDegree}deg)`;
    }

    render() {
        const { countVisible, confirmVisible, behalfVisible } = this.state;
        const { detailInfo, form: { getFieldDecorator } } = this.props;
        const { consigneePhone = '' } = detailInfo;

        return (
            <Fragment>
                <PageHeader />

                <Card bordered={false} className="paddingB10">
                    <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                        <Col md={12} sm={24} className="marginB20">
                            <div
                                className="checkImg"
                                style={{
                                    width: '100%',
                                    height: '500px',
                                    background: '#000',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    overflow: 'auto',
                                }}
                            >
                                <img
                                    id="img"
                                    src={detailInfo.imgUrl}
                                    alt=""
                                    style={{
                                        height: '100%',
                                        transition: '0.5s',
                                    }}
                                />
                            </div>
                            <div className="marginT20">
                                <Button
                                    type="primary"
                                    icon={<ZoomInOutlined />}
                                    className="marginR16"
                                    onClick={() => this.handleChangeImgSize(0.2)}
                                >
                                    放大
                                </Button>
                                <Button
                                    type="primary"
                                    icon={<ZoomOutOutlined />}
                                    className="marginR16"
                                    danger
                                    onClick={() => this.handleChangeImgSize(-0.2)}
                                >
                                    缩小
                                </Button>
                            </div>
                        </Col>
                        <Col md={12} sm={24}>
                            <div className="checkLogo" style={{ marginBottom: 20, display: 'flex' }}>
                                <img
                                    src={detailInfo.expressImg}
                                    alt=""
                                    className={detailInfo.expressImg ? 'marginR16' : ''}
                                    style={detailInfo.expressImg ? { width: 80 } : {}}
                                />
                                <Descriptions column={1} className="marginT12">
                                    <Descriptions.Item label="已完成校验">{detailInfo.checkedCount}</Descriptions.Item>
                                    <Descriptions.Item label="待校验总数">{detailInfo.uncheckCount}</Descriptions.Item>
                                </Descriptions>
                            </div>
                            <Row gutter={20}>
                                <Col span={24}>
                                    <Button
                                        className="marginR16 marginB12"
                                        onClick={() => this.handleRotating(90)}
                                    >
                                        顺时针旋转90度
                                    </Button>
                                    <Button
                                        className="marginR16 marginB12"
                                        onClick={() => this.handleRotating(-90)}
                                    >
                                        逆时针旋转90度
                                    </Button>
                                    <Button
                                        className="marginR16 marginB12"
                                        onClick={() => this.handleRotating(180)}
                                    >
                                        180度旋转
                                    </Button>
                                </Col>
                            </Row>
                            <Row gutter={20}>
                                <Col span={24}>
                                    <Button
                                        type="primary"
                                        onClick={this.handleShowCountModal}
                                    >
                                        设为待盘点
                                    </Button>
                                </Col>
                            </Row>
                            <Descriptions column={1} className="marginT24">
                                <Descriptions.Item label="　运单号">{detailInfo.expCode}</Descriptions.Item>
                                <Descriptions.Item label="手机号码">
                                    {
                                        getFieldDecorator('consigneePhone', {
                                            initialValue: String(consigneePhone).substring(0, 3),
                                        })(
                                            <Input
                                                allowClear
                                                type="number"
                                                maxLength={11}
                                                className="ocrPhoneInput"
                                                placeholder="请输入11位手机号"
                                                style={{ width: 255 }}
                                            />,
                                        )
                                    }
                                </Descriptions.Item>
                                <Descriptions.Item>
                                    <Space>
                                        {!!detailInfo.isReplaceSms && <Button
                                            type="default"
                                            onClick={() => { this.handleShowBehalfConfirmModal(true); }}
                                        >
                                            隐私号码
                                        </Button>}
                                        <Button
                                            type="primary"
                                            onClick={this.handleConfirm}
                                            onKeyDown={(e) => this.handleOnKeyDownConfirm(e)}
                                        >
                                            确认
                                        </Button>
                                    </Space>
                                </Descriptions.Item>
                            </Descriptions>
                        </Col>
                    </Row>
                </Card>

                <Modal
                    visible={countVisible}
                    title="确认提示"
                    onOk={this.handleSetCounting}
                    onCancel={this.handleCloseCountModal}
                >
                    <p>确定要将当前订单信息设为待盘点吗？</p>
                </Modal>

                <Modal
                    visible={confirmVisible}
                    title="确认提示"
                    onOk={this.handleConfirm}
                    onCancel={() => this.handleShowConfirmModal(false)}
                >
                    <p>是否要确认当前订单？</p>
                </Modal>

                <Modal
                    width={400}
                    visible={behalfVisible}
                    title="确定使用代发通知功能？"
                    onOk={this.handleBehalfConfirm}
                    onCancel={() => this.handleShowBehalfConfirmModal(false)}
                >
                    <Space style={{ alignItems: 'start', color: '#FF0101' }}>
                        <div>注意:</div>
                        <div>
                            <p style={{ textAlign: 'left' }}>1.代发通知功能仅发送短信通知并收取短信费</p>
                            <p style={{ textAlign: 'left' }}>2.代发通知功能系统将自动补录手机号</p>
                        </div>
                    </Space>
                </Modal>
            </Fragment>
        );
    }
}

export default Form.create<OcrCheckProps>()(ocrCheckInfo);
